package com.sskj.ffex.v.activity;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lzy.okgo.OkGo;
import com.sskj.ffex.MyAppLication;
import com.sskj.ffex.R;
import com.sskj.ffex.common.App;
import com.sskj.ffex.common.AppManager;
import com.sskj.ffex.common.Constants;
import com.sskj.ffex.common.TabItem;
import com.sskj.ffex.common.rxbus2.RxBus;
import com.sskj.ffex.common.rxbus2.Subscribe;
import com.sskj.ffex.common.rxbus2.ThreadMode;
import com.sskj.ffex.common.widget.MyTabLayout;
import com.sskj.ffex.common.widget.NoticeDialog;
import com.sskj.ffex.m.bean.AppVersionBean;
import com.sskj.ffex.m.bean.Currency;
import com.sskj.ffex.m.bean.Time;
import com.sskj.ffex.m.bean.UserInfo;
import com.sskj.ffex.m.bean.bean.NewStock;
import com.sskj.ffex.m.bean.rxbus.StockLevel;
import com.sskj.ffex.p.activity.MainPresenter;
import com.sskj.ffex.utils.APKVersionCodeUtils;
import com.sskj.ffex.utils.SPUtils;
import com.sskj.ffex.utils.ToastUtil;
import com.sskj.ffex.v.base.BaseActivity;
import com.sskj.ffex.v.fragment.AppUpDateFragment;
import com.sskj.ffex.v.fragment.FabiFragment;
import com.sskj.ffex.v.fragment.LevelTransactionFragmentX;
import com.sskj.ffex.v.fragment.MarketFragment;
import com.sskj.ffex.v.fragment.MineFragment;

import java.util.ArrayList;
import java.util.Stack;

import butterknife.BindView;
import butterknife.OnClick;
import sskj.lee.appupdatelibrary.BaseUpdateDialogFragment;
import sskj.lee.appupdatelibrary.BaseVersion;

/**
 * create by Hey at 2018/5/3 18:45
 */
public class MainActivity extends BaseActivity<MainPresenter> {

    @BindView(R.id.mainContent)
    FrameLayout mTabcontent;
    @BindView(R.id.tabLayout)
    MyTabLayout tabLayout;
    @BindView(R.id.main_drawer_layout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.main_left_drawer_layout)
    LinearLayout mLeftLayout;
    public UserInfo mUserInfo;
    public boolean mDrawerIsOpen;
    public Object mCurrentStock;
    public Currency mCurrency = Currency.BTC;
    public StockLevel stockLevel;
//    /**
//     * 0 买 1 卖
//     */
//    public int status;

    private onDrawOpenListener listener;

    ArrayList<Fragment> fragmentList = new ArrayList<>();

    public boolean mTransactionFragmentUp = false;

    NoticeDialog dialog;
    Runnable runnable;
    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    public String mCurrentStockName;

    public int index;
    public boolean mIsTransactionOpenDrawer = false;
    /**
     * 币币交易专用的数据
     */
    public Object mTransactionCurrentStock;
    public String mTransactionCurrentStockName;


    private onDrawOpenListener onDrawOpenListener;
    /**
     * 0 买 1 卖
     */
    public int status;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    public MainPresenter getPresenter() {
        return new MainPresenter();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (checkLogin()) {
            if (index == 0) {
                MarketFragment fragment = (MarketFragment) getSupportFragmentManager().findFragmentByTag(MarketFragment.class.getSimpleName());
                fragment.openWebSocket();
            }
        }

    }

    public boolean checkLogin() {
        if (!TextUtils.isEmpty(MyAppLication.getMobile()) & MyAppLication.isLogin()) {
            mPresenter.upDateUserInfo(MyAppLication.getMobile()); //更新用户数据
            return true;
        } else {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();
            return false;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int currentIndex = intent.getIntExtra("index", 0);
//        this.status = intent.getIntExtra("type", 0);
        if (currentIndex == 2) {
            mUserInfo = (UserInfo) SPUtils.getBean(mActivity, Constants.SP_USER_INFO);
            tabLayout.setCurrentTab(currentIndex);
        } else {
            tabLayout.setCurrentTab(currentIndex);
        }

    }

    @Override
    protected void initData() {
        if (checkLogin()) {
            initFragment();
            mPresenter.getNotice();
            mPresenter.getVersion();
        }
    }

    @Override
    protected void onViewBinding() {
        mUserInfo = (UserInfo) SPUtils.getBean(mActivity, Constants.SP_USER_INFO);
        RxBus.getDefault().register(this);
//        mPresenter.getNotice();
        //设置菜单内容之外其他区域的背景色
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);//禁止滑动开启
        mDrawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerOpened(View drawerView) {
                if (listener != null) {
                    listener.onOpen();
                }
                mDrawerIsOpen = true;
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                mDrawerIsOpen = false;
                if (listener != null) {
                    listener.onClose();
                }
            }
        });
    }

    private void initFragment() {
        fragmentList.add(new MarketFragment());
        fragmentList.add(LevelTransactionFragmentX.newInstance());
        fragmentList.add(FabiFragment.newInstance());
        fragmentList.add(new MineFragment());
        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.strMainActivity202), R.mipmap.icon_market_nor, R.mipmap.icon_market_pre));
        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.strMainActivity203), R.mipmap.icon_transaction_nor, R.mipmap.icon_transaction_pre));
        tabEntities.add(new TabItem(getString(R.string.c2c), R.mipmap.fbjy, R.mipmap.fbjy_1));
//        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.strMainActivity206), R.mipmap.icon_level_transaction_nor, R.mipmap.icon_level_transaction_pre));
        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.strMainActivity207), R.mipmap.icon_mine_nor, R.mipmap.icon_mine_pre));
        tabLayout.setTabData(tabEntities, this, R.id.mainContent, fragmentList);
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                index = position;
                mUserInfo = (UserInfo) SPUtils.getBean(mActivity, Constants.SP_USER_INFO);
                upDateFragment(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }

    public void upDateFragment(int index) {

        if (index == 0 | index == 1) {
            mIsTransactionOpenDrawer = false;
        }

        if (index == 1) {
            LevelTransactionFragmentX levelTransactionFragment = (LevelTransactionFragmentX) getSupportFragmentManager().findFragmentByTag(LevelTransactionFragmentX.class.getSimpleName());
            if (levelTransactionFragment != null) {
                levelTransactionFragment.upDate();
                levelTransactionFragment.updateFragment();
            }
            MarketFragment fragment = (MarketFragment) fragmentList.get(0);
            if (fragment != null) {
                fragment.openWebSocket();
            }
        }

        if (index > 1) {
            MarketFragment fragment = (MarketFragment) fragmentList.get(0);
            if (fragment != null) {
                fragment.closeWebSocket();
            }
        }
    }

    public void upDateLevelFragment() {
        LevelTransactionFragmentX levelTransactionFragment = (LevelTransactionFragmentX) getSupportFragmentManager().findFragmentByTag(LevelTransactionFragmentX.class.getSimpleName());
        if (levelTransactionFragment != null) {
            levelTransactionFragment.updateTopView(true);
        }
    }

    /**
     * @param context c
     * @param index   要跳转的页面index
     * @param type    0 买 1卖
     */
    public static void start(Context context, int index, int type) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("index", index);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    public void openDrawerLayout() {
        mDrawerLayout.openDrawer(Gravity.LEFT);
    }

    public void closeDrawerLayout() {
        mDrawerLayout.closeDrawers();
    }

    @OnClick(R.id.main_left_close)
    public void onViewClick() {
        mDrawerLayout.closeDrawers();
    }


    /**
     * 更新用户信息
     *
     * @param user 用户信息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUserInfo(UserInfo user) {
        if (user != null) {
            mUserInfo = user;
            SPUtils.putBean(mActivity, Constants.SP_USER_INFO, user);
        }
    }

    /**
     * 更新最新币种数据
     *
     * @param stock    币
     * @param currency 类型
     */
    public void updateCurrentStock(Object stock, Currency currency) {
        this.mCurrency = currency;
        this.mCurrentStock = stock;
        if (currency == Currency.BTC) {
            NewStock newStock = (NewStock) stock;
            mCurrentStockName = newStock.getName();
            if (newStock.getName().toUpperCase().contains("ETH") | newStock.getName().toUpperCase().contains("BTC")) {
                mTransactionCurrentStockName = newStock.getName();
                mTransactionCurrentStock = stock;
            }
        } else if (currency == Currency.TIME) {
            mTransactionCurrentStockName = mCurrentStockName = ((Time) stock).getPname();
            mTransactionCurrentStock = stock;
        }
    }

    public void setOnDrawOpenListener(onDrawOpenListener onDrawOpenListener) {
        this.listener = onDrawOpenListener;
    }

    public void onVersionDataSuccess(AppVersionBean versionBean) {
        if (versionBean == null) {
            return;
        }
        if (!this.getClass().getName().equals(getTopActivity(this))) {
            return;
        }

        String verName = APKVersionCodeUtils.getVerName(this);
        versionBean.setViewStyle(BaseVersion.NOTIFYCATION_STYLE);

        if (APKVersionCodeUtils.compareVersion(versionBean.getVersion(), verName) == 1) {
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            getFragmentManager().beginTransaction();
            AppUpDateFragment appUpDateFragment = new AppUpDateFragment();//自定义UI
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseUpdateDialogFragment.INTENT_KEY, versionBean);
            appUpDateFragment.setArguments(bundle);
            appUpDateFragment.show(fragmentTransaction, "update");
        }
    }


    public interface onDrawOpenListener {
        void onOpen();

        void onClose();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.MARKET:
                    onNewIntent(data);
                    break;
                case Constants.PAY_PWD_INPUT:
                    LevelTransactionFragmentX fragment = (LevelTransactionFragmentX) getSupportFragmentManager().findFragmentByTag(LevelTransactionFragmentX.class.getSimpleName());
                    if (fragment != null) {
                        fragment.onActivityResult(requestCode, resultCode, data);
                    }
                    break;
            }
        }

    }


    public void showNotice(String tpgg) {
        dialog = new NoticeDialog.Builder(this)
                .cancelable(false)
                .canceledOnTouchOutside(false)
                .loadText(tpgg)
                .build();
        if (isRunning(this)) {
            dialog.show();
            Handler handler = new Handler();
            runnable = new Runnable() {
                int i = 4;

                @Override
                public void run() {
                    if (i != 0) {
                        handler.postDelayed(runnable, 1000);
                        dialog.getButton().setText("(" + i + ")" + App.INSTANCE.getString(R.string.strMainActivity215));
                        dialog.getButton().setEnabled(false);
                        i--;
                    } else {
                        dialog.getButton().setText(App.INSTANCE.getString(R.string.strMainActivity215));
                        dialog.getButton().setEnabled(true);
                    }
                }
            };
            handler.postDelayed(runnable, 1000);
        }

    }

    public boolean checkPwdStatus() {
        if (mUserInfo != null) {
            if (mUserInfo.tpwd != null && mUserInfo.tpwd.equals("1")) {
                return true;
            } else {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strMainActivity218));
                startActivity(new Intent(mActivity, SecurityCenterActivity.class));
                return false;
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        RxBus.getDefault().unregister(this);
        OkGo.getInstance().cancelTag(this);
        super.onDestroy();
    }

    private static long mPreTime;

    /**
     * 统一退出控制
     */
    @Override
    public void onBackPressed() {
        Stack<Activity> allActivities = AppManager.getAppManager().getAllActivities();
        if (mDrawerIsOpen) {
            mDrawerLayout.closeDrawers();
            return;
        }
        if (allActivities.size() <= 1) {
            if (System.currentTimeMillis() - mPreTime > 2000) {// 两次点击间隔大于2秒
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strMainActivity219));
                mPreTime = System.currentTimeMillis();
                return;
            }
        }
        super.onBackPressed();
    }

    //判断当前界面显示的是哪个Activity
    public static String getTopActivity(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        Log.d("Chunna.zheng", "pkg:" + cn.getPackageName());//包名
        Log.d("Chunna.zheng", "cls:" + cn.getClassName());//包名加类名
        return cn.getClassName();
    }
}
